package com.zzf.concurrent.example.keyword;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/8/14 20:06
 */
@Slf4j
public class VolatileExample {

    /**
     * volatile并不能保证线程安全
     * volatile关键字作用:
     * 1.保证变量对所有的线程的可见性
     * 2.禁止指令重排序优化
     */
    private static volatile int count;
    public static final int MAX_COUNT = 5;

    public static void main(String[] args) {

        new Thread(() -> {
            int tempCount = count;
            while (count <= MAX_COUNT) {
                if (count != tempCount) {
                    log.info("[{}]: count is updated {}", Thread.currentThread().getName(), count);
                    tempCount = count;
                }
                // 延时1毫秒，或者使用System.out.print打印一下， 效果和volatile一样，jvm会在cpu空闲时，尽可能的刷新cpu内存的变量
                // TimeUtil.sleep(1);
            }
        }, "t1").start();

        new Thread(() -> {
            int updateCount = count;
            while (count <= MAX_COUNT) {
                count = ++updateCount;
                log.info("[{}]: count is updating {}", Thread.currentThread().getName(), count);
                TimeUtil.sleep(500);
            }
        }, "t2").start();
    }

}
